<template>
  <el-container>
    <el-main>
      <el-form el-form ref="form" :model="searchList">
        <el-row>
          <el-col :span="4">
            <el-form-item label="用户名">
              <el-input v-model="searchName" style="width: 200px"></el-input>
            </el-form-item>
          </el-col>

          <!-- <el-col :span="4">
            <el-form-item label="用户类型">
              <el-select placeholder="请选择用户类型" v-model="searchClass">
                <el-option label="管理员" value="1"></el-option>
                <el-option label="普通用户" value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col> -->
          <el-col :span="4">
            <el-form-item>
              <el-button type="primary" @click="search">搜索</el-button>
              <el-button @click="reset">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <!-- <el-table-column type="selection" width="55"> </el-table-column> -->

        <el-table-column prop="username" label="用户名" width="120"></el-table-column>
        <!--
        <el-table-column prop="password" label="密码" show-overflow-tooltip>
        </el-table-column>
        -->
        <el-table-column
          prop="status"
          label="用户类型"
          width="120"
          :formatter="statusFormatter"
          column-key="status"
          :filters="[
            { text: '管理员', value: '1' },
            { text: '普通用户', value: '2' }
          ]"
          :filter-method="filterHandler"
          :filter-multiple="false"
        ></el-table-column>
        <el-table-column
          prop="createTime"
          label="注册时间"
          show-overflow-tooltip
          :formatter="yearMouthFormatter"
        ></el-table-column>
        <!--
 
  <el-table-column label="日期" width="120">
          <template slot-scope="scope">{{ scope.row.date }}</template>  </el-table-column>
-->

        <el-table-column label="操作" v-if="role()">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog title="更新用户状态" :visible.sync="dialogFormVisible">
        <el-form :model="form">
          <el-form-item label="用户类型" :label-width="formLabelWidth">
            <el-select v-model="form.status" placeholder="请选择用户类型" style="width: 180px">
              <el-option label="管理员" value="1"></el-option>
              <el-option label="普通用户" value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="密码(可选)" :label-width="formLabelWidth">
            <el-input type="password" v-model="form.password" style="width: 180px"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="handleEditCancel">取 消</el-button>
          <el-button type="primary" @click="handleEditCommit">确 定</el-button>
        </div>
      </el-dialog>
    </el-main>

    <!-- 页脚分页 -->
    <div class="fenye">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
  </el-container>
</template>

<script>
export default {
  name: 'User',
  data() {
    return {
      allData: [],
      tableData: [],
      page: 1, //页脚显示的当前页
      size: 10, //一页多少条数据
      total: 400, //总条目数
      multipleSelection: [], //当前选中的行

      searchList: {
        //搜索条件的
        uname: '',
        uclass: ''
      },
      searchName: '',
      searchClass: '',
      dialogFormVisible: false, //弹出的修改表单
      form: {
        id: '',
        status: '',
        password: ''
      },
      formLabelWidth: '120px' //宽度
    }
  },
  watch: {
    searchClass: {
      handler(newVal, oldVal) {
        let url = '/securityUser/queryAll' + newVal
        this.$request.get(url).then(res => {
          this.allData = res.data.obj
          this.getTableData() //获取信息后更新表单数据
        })
      }
    }
  },
  methods: {
    filterHandler(value, row, column) {
      console.log('data:', value, row, column)
      const property = column['property']
      return row[property] == value
    },
    role() {
      // console.log("111");
      const role = window.sessionStorage.getItem('authority')
      // console.log(role);
      if (role == 'ROLE_admin') {
        return true
      }
      return false
    },
    //分页表格数据
    getTableData() {
      //allData为全部数据
      console.log(this.allData)
      this.tableData = this.allData.slice((this.page - 1) * this.size, this.page * this.size)
      this.total = this.allData.length //总条目等于allDaTa长度
    },
    //size改变时的回调，参数为当前的size
    handleSizeChange(val) {
      // console.log("改变每页多少条，当前一页多少条", val);
      this.size = val
      this.page = 1 //size改变时要把page重置为1，再把参数赋值给size，因为size改变会导致page数量改变
      this.getTableData()
    },
    //page改变时的回调函数，参数为当前页码
    handleCurrentChange(val) {
      // console.log("翻页，当前为第几页", val);
      this.page = val
      this.getTableData()
    },

    //请求所有的用户信息
    getAllSecurityUser() {
      this.$request.get('securityUser/queryAll').then(res => {
        // console.log(res);
        if (res.data.obj != null) {
          // console.log(res.data.obj);
          this.allData = res.data.obj
          // console.log(this.allData);
          this.getTableData() //获取信息后更新表单数据
        } else {
          this.$message.error('信息获取失败')
        }
      })
    },
    //获取管理员的信息
    get1SecurityUser() {
      this.$request.get('securityUser/queryAll1').then(res => {
        if (res.data.obj != null) {
          this.allData = res.data.obj
          this.getTableData() //获取信息后更新表单数据
        } else {
          this.$message.error('信息获取失败')
        }
      })
    },
    //获取普通用户的信息
    get2SecurityUser() {
      this.$request.get('securityUser/queryAll2').then(res => {
        if (res.data.obj != null) {
          this.allData = res.data.obj
          this.getTableData() //获取信息后更新表单数据
        } else {
          this.$message.error('信息获取失败')
        }
      })
    },
    getSecurityUserByName(username) {
      this.$request
        .post('securityUser/queryByUsername', {
          username: username
        })
        .then(res => {
          if (res.data.obj != null) {
            // this.tableData = res.data.obj;
            // console.log(res.data.obj);
            // console.log(this.tableData);
            this.tableData = []
            this.tableData.push(res.data.obj)
            // console.log(this.tableData);
          } else {
            this.$message.error('查无此人')
            this.reset()
          }
        })
    },

    // URLDecodeFormatter(row) {
    //   let a = row.password;
    //   a = a.toString();
    //   return decodeURIComponent(a);
    // },

    // 格式化用户类型
    statusFormatter(row, column) {
      if (row.status === 1) {
        return '管理员'
      } else if (row.status === 2) {
        return '普通用户'
      } else {
        return '未知'
      }
    },
    // 格式化日期
    yearMouthFormatter(row, column) {
      let date = new Date(row.createTime)
      let dateF = this.formatDate(date)
      return dateF
    },
    formatDate(current_datetime) {
      const date = this.SimpleDateFormat(current_datetime).format('YYYY-MM-DD HH:mm:ss')
      return date
    },
    search() {
      // console.log(this.searchList.uclass)
      // if (this.searchList.uclass == 1 && this.searchList.uname == '') {
      //   this.get1SecurityUser()
      // } else if (this.searchList.uclass == 2 && this.searchList.uname == '') {
      //   this.get2SecurityUser()
      // } else if (this.searchList.uname != '') {
      this.getSecurityUserByName(this.searchName)
    },
    reset() {
      this.getAllSecurityUser()
      this.searchList.uname = ''
      this.searchList.uclass = ''
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleEdit(index, row) {
      console.log(row.id)
      this.dialogFormVisible = true
      this.form.id = row.id
    },
    handleDelete(index, row) {
      // console.log(index, row);
      console.log(row.id)
      this.$request.get('securityUser/deleteById/' + row.id).then(res => {
        if (res.data.obj) {
          this.$message('删除成功')
          this.reset()
        } else {
          this.$message.error('删除失败失败')
        }
      })
    },
    handleEditCommit() {
      this.dialogFormVisible = false
      if (this.form.status != '' && this.form.password == '') {
        this.$request
          .post('/securityUser/admin-update', {
            id: this.form.id,
            status: this.form.status
          })
          .then(res => {
            if (res.data.obj) {
              this.$message.success('修改成功')
              this.handleEditCancel()
              this.reset()
            } else {
              this.$message.error('修改失败')
            }
          })
      } else if (this.form.status != '' && this.form.password != '') {
        this.$request
          .post('/securityUser/admin-update', {
            id: this.form.id,
            status: this.form.status,
            password: this.form.password
          })
          .then(res => {
            if (res.data.obj) {
              this.$message.success('修改成功')
              this.handleEditCancel()
              this.reset()
            } else {
              this.$message.error('修改失败')
            }
          })
      } else {
        this.$message.warning('未发生变更')
      }
    },
    handleEditCancel() {
      this.dialogFormVisible = false
      this.form.id = ''
      this.form.status = ''
    }
  },
  mounted() {
    this.getTableData()
    this.getAllSecurityUser()
  }
}
</script>

<style scoped>
.el-header {
  background-color: rgb(42, 53, 66);
  color: #fff;
  line-height: 60px;
}

.el-aside {
  color: #333;
}
.el-col {
  /* background-color: #fff; */
  color: #fff;
}
i {
  font-size: 18px;
}
.fenye {
  position: fixed;
  bottom: 10px;
}
</style>
